<template>
  <div :id="comId" @layout="comChanges">
    <slot :cacheId="state.cacheFocusId" :isBoxFocus="isFocus"></slot>
  </div>
</template>
<script>
import { getUUid, getCommentInfo } from "@/hippy-focus/path/utils";
import Vue from "vue";
export default {
  name: "focus-content",
  components: {},
  provide() {
    return {
      focusBoxState: this.state,
      focusBoxMethods: {
        getId: () => this.$el.id
      },
    }
  },
  inject: {
    focusSwitchState: {
      default: {},
    },
    focusSwitchMethods: {
      default: {},
    },
    $focusWidgets: {
      default: {}
    },
  },
  props: {
    cacheid: {
      type: String,
      default: "",
    },
    iscache: {
      type: Boolean,
      default: true
    },
  },
  model: {
    prop: "cacheid",
    event: "cachechange",
  },
  emits: ["cachechange"],
  data() {
    return {
      comId: getUUid(),
      state: {
        isFocus: false,
        cacheFocusId: "",
      },
    };
  },
  beforeCreate() {

  },
  created() {

  },
  mounted() {

  },
  computed: {

  },
  beforeDestroy() {
    this.comChanges({}, true)
  },
  methods: {
    //焦点生命周期，返回true拦截焦点跳转，返回焦点id则跳转到指定焦点
    beforeFocusChange(nextFocus, _keycode) {
      const _cacheId = this.reSetFocusIdByCache(nextFocus)
      if (_cacheId) return _cacheId
    },
    //焦点修改之后生命周期
    afterFocusChange(oldFocus, _keycode) {

    },
    //进入盒子时，重置焦点到缓存的焦点
    reSetFocusIdByCache(nextFocus) {
      if (!this.iscache) return;
      const _nowWidget = this.$focusWidgets[this.focusSwitchState.focusId]
      const _nextWidget = this.$focusWidgets[nextFocus]
      if(!_nowWidget || !_nextWidget) return
      if (_nowWidget.boxId !== this.$el.id && _nextWidget.boxId === this.$el.id) return this.state.cacheFocusId
    },
    comChanges(postion = {}, isdelete = false) {
      const _info = getCommentInfo(this, { postion, isdelete })
      if (typeof this.focusSwitchMethods.otherComChange === 'function') {
        this.focusSwitchMethods.otherComChange(_info)
      } else {
        console.error('box组件必须包裹在switch组件内')
      }
    },
  },
  watch: {
    "focusSwitchState": {
      handler(state) {
        const _widget = this.$focusWidgets[state.focusId];
        this.isFocus = _widget && _widget.boxId === this.$el.id;
        if (this.isFocus) this.state.cacheFocusId = _widget.id
      },
      deep: true,
      immediate: true,
    },
    "cacheid": {
      handler(newVal) {
        this.state.cacheFocusId = newVal;
      },
      immediate: true,
    },
    "state.cacheFocusId": {
      handler(newVal) {
        this.$emit("cachechange", newVal)
      },
      immediate: true,
    },
  },
};
</script>